using System;
using System.Collections.Generic;
using System.Text;

using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;
using UncleGED;
using UncleGED.Application;
using UncleGED.Collections;
using UncleGED.Documentation;
using UncleGED.Utils;

namespace UGed
{
   class Program
   {
      //global stream writer for the log file
      public static StreamWriter g_sw;

      static int Main(string[] args)
      {
         string gedcomFile = "";
         string configXmlFile = "";
         GedReader gr;
         TimeSpan tsStart;
         TimeSpan tsStop;
         double totalTime;
         int retVal = 0;

         //read the default settings from the xml config file
         UGedProject configSettings = new UGedProject();
         LocalApplication localSettings = new LocalApplication();

         //string funcs class contains functions ported from VB6
         //see notes in read-me
			StringFunctions sf = new StringFunctions();

         //start a log file
         string sPath = FolderMethods.GetAppPath();
         string sLogFile = sPath + "\\date_est_test.log";
         g_sw = new System.IO.StreamWriter(sLogFile);
         Trace.Listeners.Add(new TextWriterTraceListener(g_sw));
         Trace.AutoFlush = true;

         configSettings = new UGedProject();
         localSettings = ConfigReader.LoadSettings(sPath + "\\projects.cfg");

         //write out the version
         Console.Write("UncleGED Date Estimation Tool - Ver. ");
         Console.WriteLine(System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion);

#if (DEBUG) 
			Console.WriteLine(" (DEBUG)");
#else
         Console.WriteLine(" (RELEASE)");
#endif
         Tools.Logit("Copyright " + System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).LegalCopyright);

         if (args.Length != 0)
         {
            gedcomFile = args[0];
         }
         else
         {
            Console.WriteLine("Usage: date_est.exe gedcom_file");
            return 1;
         }

         try
         {

            configXmlFile = "_dateest.ugproj";

            Tools.Logit("Reading Configuration from...");
            Tools.Logit(configXmlFile);
            configSettings = LoadXmlSettings(configXmlFile);

            if (!(configSettings == null))
            {
               configSettings.GedComFile = gedcomFile;
               gedcomFile = configSettings.GedcomPath + "\\" + configSettings.GedComFile;
               Tools.Logit("Processing " + gedcomFile);
               tsStart = DateTime.Now.TimeOfDay;

               //the GED reader object does all the work
               // see ug_gedreader.cs
               gr = new GedReader(configSettings, localSettings, gedcomFile);

               gr.StatusMessage += new StatusMessageEventHandler(GedReader_StatusMessage);

               //process the data
               if (gr.ProcessGedComFile(gedcomFile, true) == true)
               {
                  gr.EstimateBirthDates();
                  Tools.Logit("Saving estimated dates listing file...");
                  gr.SaveEstimatedDatesList();
               }
               else
               {
                  retVal = -1;
                  goto END_THIS_THING;
               }
               tsStop = DateTime.Now.TimeOfDay;
               totalTime = tsStop.TotalSeconds - tsStart.TotalSeconds;
               Tools.Logit("Total time to process: " + totalTime.ToString() + " seconds");
            }
            else
            {
               Tools.Logit("Error Processing XML config file!");
               retVal = -1;
               goto END_THIS_THING;
            }

            Tools.Logit("Thank you for using Uncle GED's Date Estimation Tool...");
            Tools.Logit("Y\'all come back now, y\'hear!");
         }
         catch (Exception ex)
         {
            Tools.Logit("Error trapped in Main : " + ex.Message);
            retVal = -1;
         }
      END_THIS_THING:
         try
         {
            SaveXmlSettings(configXmlFile, configSettings);
         }
         catch
         {
            //empty catch
         }
         g_sw.Close();
         return retVal;
      }

      private static void GedReader_StatusMessage(object sender, StatusMessageArgs e)
      {
         if (e.IsProgress == false)
         {
            Console.WriteLine(e.Message);
         }
      }

      /// <summary>
      /// Summary of SaveXmlSettings.
      /// </summary>
      /// <param name=sXmlConfig></param>
      /// <param name=ConfigSettings></param>
      /// 		
      public static void SaveXmlSettings(string sXmlConfig, UGedProject ConfigSettings)
      {
         XmlSerializer XmlS = new XmlSerializer(typeof(UGedProject));
         FileStream fStream = new FileStream(sXmlConfig, FileMode.Create);
         XmlS.Serialize(fStream, ConfigSettings);
         fStream.Close();
      }

      /// <summary>
      /// Summary of LoadXmlSettings.
      /// </summary>
      /// <param name=sXmlConfig></param>
      /// 		
      public static UGedProject LoadXmlSettings(string sXmlConfig)
      {
         UGedProject configSettings;

         try
         {
            XmlSerializer XmlS = new XmlSerializer(typeof(UGedProject));
            FileStream fStream = new FileStream(sXmlConfig, FileMode.Open);
            configSettings = (UGedProject)XmlS.Deserialize(fStream);
            fStream.Close();
            fStream = null;
            XmlS = null;
         }
         catch
         {
            configSettings = new UGedProject();
            SaveXmlSettings("default.ugproj", configSettings);
         }

         return configSettings;

      }

   }
}
